﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using qkview.Filters;
using qkview.Models;
using System.Web;
using System.Web.Helpers;
using System.Net.Mail;
using System.Configuration;
using Elmah;

namespace qkview.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

        [AllowAnonymous]
        public JsonResult doesUserNameExist(string UserName)
        {
            var user = Membership.GetUser(UserName);
            return Json(user == null, JsonRequestBehavior.AllowGet);
        }

        [AllowAnonymous]
        public JsonResult doesEmailExist(string Email)
        {
            bool ret;
            using (var context = new QKVEntities())
            {
                ret  = context.UserProfiles.Any(u => u.Email == Email);
               
            }
            return Json(!ret, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }


        //
        // POST: /Account/Login

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {

                if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
                {

                    using (QKVEntities db = new QKVEntities())
                    {
                        var isBlocked = db.UserProfiles.FirstOrDefault(x => x.UserName == model.UserName).IsBlocked;
                        isBlocked = isBlocked ?? false;
                        if (isBlocked.Value)
                        {
                            WebSecurity.Logout();
                            ModelState.AddModelError("", "This user is currently blocked.");
                        }
                        else
                        {

                            int userID = WebSecurity.GetUserId(model.UserName);
                            Session["setting"] = Common.GetUserSetting();
                            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                            return RedirectToLocal(returnUrl);                            
                        }
                    }                
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect or not verified.");
                }
            }
            // If we got this far, something failed
            return View(model);
        }


               
        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }



        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }


        //
        // POST: /Account/JsonRegister
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model, string returnUrl)
        {


            using (var context = new QKVEntities())
            {
                if (context.UserProfiles.Any(u => u.UserName == model.UserName))
                {
                    ModelState.AddModelError("", "User Name already exists");
                }
                if (context.ReservedUserNames.Any(u => u.Name.ToLower() == model.UserName.ToLower() && (u.IsUsed == null || u.IsUsed == false)))
                {
                    ModelState.AddModelError("", "This User Name is already reserved");
                }
                if (context.UserProfiles.Any(u => u.Email == model.Email))
                {
                    ModelState.AddModelError("", "Email already exists");
                }
                if (ModelState.IsValid)
                {


                    // Attempt to register the user
                    try
                    {
                        string confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                            new { Email = model.Email, Name = model.Name }, true);
                        var confirmationUrl = Url.Action("RegisterConfirmation", "Account", null, protocol: Request.Url.Scheme) + "?username=" + HttpUtility.UrlEncode(model.UserName) + "&Id=" + HttpUtility.UrlEncode(confirmationToken);
                        var confirmationLink = String.Format("<a href=\"{0}\">Click to confirm your registration</a>", confirmationUrl);

                        string emailBodyText =
                             "<p>Thank you for signing up with us! "
                             + "Please confirm your registration by clicking the following link:</p>"
                             + "<p>" + confirmationLink + "</p>"
                             + "<p>In case you need it, here's the confirmation code:<strong> "
                             + confirmationToken
                             + "</strong></p>";
               
                        SendEMail(model.Email, "Qkview Account Confirmation", emailBodyText);

                        ViewBag.Message = String.Format(
                         "Thank you for registering. An email has been sent to {0}. " +
                         "Please check your email and use the enclosed link to finish registration.",
                         model.Email);
                        //To clear form fields
                        ModelState.Clear();  

                        ModelState.AddModelError("", ViewBag.Message);                    
                        return View(model:null);
                    }
                    catch (MembershipCreateUserException e)
                    {
                        ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                        ErrorSignal.FromCurrentContext().Raise(e);
                    }
                }
            }

            // If we got this far, something failed
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult RegisterConfirmation(string userName, string Id)
        {
            if (WebSecurity.ConfirmAccount(userName, Id))
            {
                //InitiateDatabaseForNewUser(model.UserName);
                ViewBag.Message = "You have confirmed mail successfully, please login to continue.";
            }
            else
            {
                ViewBag.Message = "Confirmation failed";
            }
            return View("Message");
        }

        [AllowAnonymous]
        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ForgotPassword(string UserName)
        {
            //check user existance
            var user = Membership.GetUser(UserName);
            if (user == null)
            {
                ViewBag.Message = "User doesn't exist.";
            }
            else
            {
                //generate password token
                var token = WebSecurity.GeneratePasswordResetToken(UserName);
                //create url with above token
                var resetLink = "<a href='" + Url.Action("ResetPassword", "Account", new { u = UserName, r = token }, "http") + "'>Reset Password</a>";
                //get user emailid
                using (QKVEntities db = new QKVEntities())
                {
                    var emailid = (from i in db.UserProfiles
                                   where i.UserName == UserName
                                   select i.Email).FirstOrDefault();

                    //send mail
                    string subject = "QKView Password Reset Token";
                    string body = "<b>Please find the Password Reset Token for qkview.com </b><br/>" + resetLink; //edit it
                    try
                    {
                        SendEMail(emailid, subject, body);
                        ViewBag.Message = "An email has been sent to your email address to reset the password";
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = "Error occured while sending email." + ex.Message;
                        ErrorSignal.FromCurrentContext().Raise(ex);
                    }
                }
                //only for testing
                //ViewBag.Message  = resetLink;
            }

            return View();
        }

        [AllowAnonymous]
        public ActionResult ResetPassword(string u, string r)
        {
            using (QKVEntities db = new QKVEntities())
            {
                //TODO: Check the un and rt matching and then perform following
                //get userid of received username
                var userid = (from i in db.UserProfiles
                              where i.UserName == u
                              select i.UserId).FirstOrDefault();
                //check userid and token matches
                bool any = (from j in db.webpages_Membership
                            where (j.UserId == userid)
                            && (j.PasswordVerificationToken == r)
                            //&& (j.PasswordVerificationTokenExpirationDate < DateTime.Now)
                            select j).Any();

                if (any == true)
                {
                    //generate random password
                    string newpassword = GenerateRandomPassword(6);
                    //reset password
                    bool response = WebSecurity.ResetPassword(r, newpassword);
                    if (response == true)
                    {
                        //get user emailid to send password
                        var emailid = (from i in db.UserProfiles
                                       where i.UserName == u
                                       select i.Email).FirstOrDefault();
                        //send email
                        string subject = "New Password";
                        string body = "<b>Please find the New Password</b><br/>" + newpassword; //edit it
                        try
                        {
                            SendEMail(emailid, subject, body);
                            ViewBag.Message = "Mail Sent.";
                        }
                        catch (Exception ex)
                        {
                            ViewBag.Message = "Error occured while sending email." + ex.Message;
                            ErrorSignal.FromCurrentContext().Raise(ex);
                        }

                        //display message
                        ViewBag.Message = "Your New Password is successfully sent on your email.";
                    }
                    else
                    {
                        ViewBag.Message = "Hey, avoid random request on this page.";
                    }
                }
                else
                {

                    ViewBag.Message = "Invalid Username and Token";
                }
            }
            return View();
        }


        private void SendEMail(string emailid, string subject, string body)
        {

            MailMessage mm = new MailMessage();
            mm.From = new MailAddress(ConfigurationManager.AppSettings["mailFromAddress"]);
            mm.Subject = subject;
            mm.To.Add(emailid);
            mm.Body = body;
            mm.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.EnableSsl =(ConfigurationManager.AppSettings["isSSLForMail"].ToString() == "1");
            smtp.Send(mm);


        }

        private string GenerateRandomPassword(int length)
        {
            string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-*&#+";
            char[] chars = new char[length];
            Random rd = new Random();
            for (int i = 0; i < length; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }
            return new string(chars);
        }


        /// <summary>
        /// Initiate a new todo list for new user
        /// </summary>
        /// <param name="userName"></param>
        private static void InitiateDatabaseForNewUser(string userName)
        {
            TodoItemContext db = new TodoItemContext();
            TodoList todoList = new TodoList();
            todoList.UserId = userName;
            todoList.Title = "My Todo List #1";
            todoList.Todos = new List<TodoItem>();
            db.TodoLists.Add(todoList);
            db.SaveChanges();

            todoList.Todos.Add(new TodoItem() { Title = "Todo item #1", TodoListId = todoList.TodoListId, IsDone = false });
            todoList.Todos.Add(new TodoItem() { Title = "Todo item #2", TodoListId = todoList.TodoListId, IsDone = false });
            db.SaveChanges();
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                Common.GetUserSetting();
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                if (result.Provider == "facebook" || result.Provider == "google")
                {
                    using (QKVEntities db = new QKVEntities())
                    {
                        UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == User.Identity.Name);
                        if (user != null)
                        {
                            var oauthItem = db.webpages_OAuthMembership.FirstOrDefault(x => x.Provider == result.Provider && x.ProviderUserId == result.ProviderUserId && x.UserId == user.UserId);
                            if (oauthItem != null)
                            {
                                oauthItem.Email = result.UserName;
                                db.SaveChanges();
                            }
                        }
                    }
                } 
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
               string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
               ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
               ViewBag.ReturnUrl = returnUrl;
               var model = new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData };
               switch (result.Provider) {
                   case "facebook":
                   case "google":
                       {
                           model.Email = result.UserName;
                           model.UserName = "";
                           break;
                       }
                   case "twitter":
                       {
                           model.Email = "";
                           model.UserName = result.UserName;
                           break;
                       }
                   default:
                       break;
                
               }
               return View("ExternalLoginConfirmation", model);
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }
           


 // Insert a new user into the database
            using (QKVEntities db = new QKVEntities())
            {

                if (db.ReservedUserNames.Any(u => u.Name.ToLower() == model.UserName.ToLower() && (u.IsUsed == null || u.IsUsed == false)))
                {
                    ModelState.AddModelError("", "This User Name is already reserved");
                }
                if (ModelState.IsValid)
                {

                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                       
                        /*Modified to save email*/
                        // Insert name into the profile table
                        user = new UserProfile { UserName = model.UserName };
                        db.UserProfiles.Add(user);
                        db.SaveChanges();
                        InitiateDatabaseForNewUser(model.UserName);
                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);

                        if (!String.IsNullOrEmpty(model.Email))
                        {
                            var oauthItem = db.webpages_OAuthMembership.FirstOrDefault(x => x.Provider == provider && x.ProviderUserId == providerUserId && x.UserId == user.UserId);
                            if (oauthItem != null)
                            {
                                oauthItem.Email = model.Email;
                                db.SaveChanges();
                            }
                        }

                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
                        Common.GetUserSetting();
                        return RedirectToLocal(returnUrl);


                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private IEnumerable<string> GetErrorsFromModelState()
        {
            return ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage));
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}